import router, { asyncRoutes, constantRoutes } from '../../router/index'

// 状态
const state = () => {
  return {
    allRoutes: constantRoutes
  }
}
// mutations 修改数据方法 同步
const mutations = {
  setRoutes(state, newRoutes) {
    state.allRoutes = newRoutes
  }
}
// actions 修改数据方法 异步
const actions = {
  filterRoutes(context) {
    // console.log(context.rootState)
    // console.log(context.rootState.user.userInfo.roles.menus)
    const _menus = context.rootState.user.userInfo.roles.menus
    const _newRoutes = asyncRoutes.filter(v => {
      const _length = v.children.filter(child => {
        return _menus.includes(child.name)
      }).length
      if (_length > 0) {
        return true
      } else {
        return false
      }
    })
    // 404 page must be placed at the end !!!
    _newRoutes.push({ path: '*', redirect: '/404', hidden: true })
    console.log(_newRoutes)
    router.addRoutes(_newRoutes)
    context.commit('setRoutes', [...constantRoutes, ..._newRoutes])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
